//
//  Copyright 2011  comphilip
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
using System;
using System.IO;
using System.Reflection;

namespace DictShell {
	class MainClass {
		private const int ERROR = 1;
		private const int OK = 0;
		public static int Main(string[] args) {
			if (args.Length > 1) {
				PrintUsage(Console.Error);
				return ERROR;
			}

			int port = 2628;
			bool debug = false;
			foreach (string arg in args) {
				if (Array.Exists(new string[] {"--help", "-?", "/?", "-h"}, (x) => string.Equals(arg, x, StringComparison.OrdinalIgnoreCase))) {
					PrintUsage(Console.Out);
					return OK;
				} else if (string.Equals(arg, "--debug", StringComparison.OrdinalIgnoreCase))
					debug = true;
				else if (arg.StartsWith("--port=", StringComparison.OrdinalIgnoreCase)) {
					if (!int.TryParse(arg.Substring(7), out port) || port < 0 || port > 65535) {
						Console.Error.WriteLine(Res.InvalidPort);
						return ERROR;
					}
				}
			}

			DictServer server = new DictServer(port, debug);
			server.Start();
			while(!string.Equals("exit", Console.ReadLine(), StringComparison.OrdinalIgnoreCase)){
			}
			
			server.Stop();
			System.Diagnostics.Trace.WriteLine("DICT end");
			return OK;
		}

		private static void PrintUsage(TextWriter Writer) {
			using(Stream usageStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Usage.txt"))
			using(StreamReader reader = new StreamReader(usageStream)) {
				Writer.Write(reader.ReadToEnd());
			}
		}
	}
}

